package tools

import (
	"encoding/binary"
	"iris-wms/common/tools/consts"
	"net"
	"strconv"
	"strings"
	"time"

	"github.com/kataras/golog"
	"github.com/kataras/iris/v12"
)

/**
 * * 一些全局工具方法
 */

// []uint convert to []string
func ListOfUintToString(idList []uint) (list []string) {
	for _, v := range idList {
		list = append(list, strconv.Itoa(int(v)))
	}
	return
}

// get local machine ip
func LocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return ""
	}
	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				golog.Info("local ip=", ipnet.IP.String())
				return ipnet.IP.String()
			}
		}
	}
	return ""
}

// ---------------------------- time util start
type times string

const (
	Times            times = "2006-01-02 15:04:05"
	Times_YYYY_MM_DD times = "2006-01-02"
	Times_HH_mm_ss   times = "15:04:05"
)

// 获取当前时间 string
func (ts times) Current() string {
	return time.Unix(time.Now().Unix(), 0).Format(string(ts))
}

func (ts times) String(t time.Time) string {
	return time.Unix(time.Now().Unix(), 0).Format(string(ts))
}

// ---------------------------- byte endian convert
func UintToBytes(i uint) []byte {
	var buf = make([]byte, 8)
	binary.BigEndian.PutUint64(buf, uint64(i))
	return buf
}

func BytesToUint(buf []byte) uint {
	if buf != nil {
		return uint(binary.BigEndian.Uint64(buf))
	} else {
		return 0
	}
}

// ---------------------------- context value
func GetUserID(ctx iris.Context) uint {
	return ctx.Values().GetUintDefault(consts.UID, 0)
}

func Split2Uint(s, sep string) ([]uint, error) {
	result := make([]uint, 0)
	idListStr := strings.Split(s, ",")
	for _, v := range idListStr {
		id, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			return nil, err
		}
		result = append(result, uint(id))
	}
	return result, nil
}
